﻿var userLocation;
var place;
var selectedPlace;
var placeClicked;
var map, places, infoWindow, input, types;
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
    map: map
});
var locationPlace;
var markers = [];
var autocomplete;
var countryRestrict = { 'country': 'us' };
var MARKER_PATH = 'http://maps.google.com/mapfiles/kml/pal2/icon0';
var hostnameRegexp = new RegExp('^https?://.+?/');
var selectedTypes = [];

var MARKER_LOCATION = "http://google.com/mapfiles/ms/micons/red-pushpin.png";
var MARKER_accommodation = "http://maps.google.com/mapfiles/kml/pal2/icon20.png";
var MARKER_food = "http://maps.google.com/mapfiles/kml/pal2/icon32.png";
var MARKER_entertainment = "http://maps.google.com/mapfiles/kml/pal2/icon19.png";
var MARKER_culture = "http://maps.google.com/mapfiles/kml/pal4/icon38.png";
var MARKER_nature = "http://maps.google.com/mapfiles/kml/pal2/icon12.png";
var MARKER_shopping = "http://maps.google.com/mapfiles/kml/pal3/icon26.png";
var MARKER_sports = "http://maps.google.com/mapfiles/kml/pal2/icon49.png";
var MARKER_transp = "http://maps.google.com/mapfiles/kml/pal4/icon31.png";
var MARKER_helpful = "http://maps.google.com/mapfiles/kml/pal3/icon53.png";

var accommodation = ['lodging']
var food = ['bar','restaurant','cafe','bakery','food','store','meal_delivery',' liquor_store','meal_takeaway','grocery_or_supermarket']
var entertainment = ['movie_rental','movie_theater','casino','zoo','night_club']
var culture = ['art_gallery','church','city_hall','courthouse','museum','hindu_temple','mosque','synagogue','university','aquarium']
var nature = ['park','amusement_park']
var shopping = ['book_store','shopping_mall','shoe_store','store','jewelry_store','home_goods_store','grocery_or_supermarket','clothing_store']
var sports = ['gym','stadium']
var transp = ['airport','gas_station','taxi_stand','train_station','rv_park','parking','bus_station','car_dealer','car_rental','car_repair']
var helpful = ['bank','atm','police','health','hospital','pharmacy','doctor']

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(47.1666667,27.6),
    zoom: 13,
	
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

  input = /** @type {HTMLInputElement} */(
      document.getElementById('pac-input'));

	  infoWindow = new google.maps.InfoWindow({
      content: document.getElementById('info-content')
      });
	  
  types = document.getElementById('type-selector');
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);

  autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  places = new google.maps.places.PlacesService(map);

   google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChanged);

  // Sets a listener on a radio button to change the filter type on Places
  // Autocomplete.
  function setupClickListener(id, types) {
    var radioButton = document.getElementById(id);
    google.maps.event.addDomListener(radioButton, 'click', function() {
      autocomplete.setTypes(types);
    });
  }

  setupClickListener('changetype-all', []);
  setupClickListener('changetype-establishment', ['establishment']);
  setupClickListener('changetype-geocode', ['geocode']);
}


function onPlaceChanged() {    
    //marker.setVisible(false);
    place = autocomplete.getPlace();
    if (!place.geometry) {
        return;
    }    
    if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
    } else {
        map.setCenter(place.geometry.location);
        map.setZoom(15);  // Why 17? Because it looks good.
    }
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        icon: MARKER_LOCATION
      });
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
      });

//    infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
//    infowindow.open(map, marker);
}


function search(place, type, iconMarker) {
  var search = {
    location: place.geometry.location,
	radius: '5000',
    types: type
  };
  places.nearbySearch(search, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      //<!-- clearResults(); -->
      //clearMarkers();
      
      for (var i = 0; i < results.length; i++) {
        // var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i); 
        //var markerIcon = MARKER_PATH +'.png';
        // Use marker animation to drop the icons incrementally on the map.
        markers[i] = new google.maps.Marker({
          position: results[i].geometry.location,
          animation: google.maps.Animation.DROP,
          icon: iconMarker
        });
        // If the user clicks a hotel marker, show the details of that hotel
        // in an info window.
        markers[i].placeResult = results[i];
        google.maps.event.addListener(markers[i], 'click', showInfoWindow);
        setTimeout(dropMarker(i), i * 100);
        //<!-- addResult(results[i], i); -->
      }
    }
  });
}

// Get the place details for a hotel. Show the information in an info window,
// anchored on the marker for the hotel that the user selected.
function showInfoWindow() {
  var marker = this;
  selectedPlace = marker.placeResult;
  var link = '<%: Html.ActionLink("Go to place", "Place", "Home", new { reference ='+selectedPlace.reference+'}) %>';
  infowindow.setContent('<div><strong><a href="home/place?reference='+ selectedPlace.reference+'" >' + marker.placeResult.name + '</a></strong></br>' + marker.placeResult.address+'</div>');
        infowindow.open(map, this);
//  places.getDetails({reference: marker.placeResult.reference},
//      function(place, status) {
//        if (status != google.maps.places.PlacesServiceStatus.OK) {
//          return;
//        }
//        infoWindow.open(map, marker);
//        //buildIWContent(place);
//      });
}

function goToPlace() {
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost:58872/home/place",
        data: {reference: selectedPlace.reference},
        dataType: "json",
        success: function (data) {
            //alert(data.Name);
        },
        error: function (result) {
            //alert("Error");
        }
    });
}

function clearMarkers() {
  for (var i = 0; i < markers.length; i++) {
    if (markers[i]) {
      markers[i].setMap(null);
    }
  }
  markers = [];
}

// The START and END in square brackets define a snippet for our documentation:
// [START region_setcountry]
// Set the country restriction based on user input.
// Also center and zoom the map on the given country.
//function setAutocompleteCountry() {
//  var country = document.getElementById('country').value;
//  if (country == 'all') {
//    autocomplete.setComponentRestrictions([]);
//    map.setCenter(new google.maps.LatLng(15, 0));
//    map.setZoom(2);
//  } else {
//    autocomplete.setComponentRestrictions({ 'country': country });
//    map.setCenter(countries[country].center);
//    map.setZoom(countries[country].zoom);
//  }
//  <!-- clearResults(); -->
//  clearMarkers();
//}
//// [END region_setcountry]

function dropMarker(i) {
  return function() {
    markers[i].setMap(map);
  };
}

//function addResult(result, i) {
//  var results = document.getElementById('results');
//  var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i);
//  var markerIcon = MARKER_PATH + markerLetter + '.png';

//  var tr = document.createElement('tr');
//  tr.style.backgroundColor = (i % 2 == 0 ? '#F0F0F0' : '#FFFFFF');
//  tr.onclick = function() {
//    google.maps.event.trigger(markers[i], 'click');
//  };

//  var iconTd = document.createElement('td');
//  var nameTd = document.createElement('td');
//  var icon = document.createElement('img');
//  icon.src = markerIcon;
//  icon.setAttribute('class', 'placeIcon');
//  icon.setAttribute('className', 'placeIcon');
//  var name = document.createTextNode(result.name);
//  iconTd.appendChild(icon);
//  nameTd.appendChild(name);
//  tr.appendChild(iconTd);
//  tr.appendChild(nameTd);
//  results.appendChild(tr);
//}

//function clearResults() {
//  var results = document.getElementById('results');
//  if (results){
//	  while (results.childNodes[0]) {
//		results.removeChild(results.childNodes[0]);
//		}
//	}
//}


// Load the place information into the HTML elements used by the info window.
//function buildIWContent(place) {
//  document.getElementById('iw-icon').innerHTML = '<img class="hotelIcon" ' +
//      'src="' + place.icon + '"/>';
//  document.getElementById('iw-url').innerHTML = '<b><a href="' + place.url +
//      '">' + place.name + '</a></b>';
//  document.getElementById('iw-address').textContent = place.vicinity;

//  if (place.formatted_phone_number) {
//    document.getElementById('iw-phone-row').style.display = '';
//    document.getElementById('iw-phone').textContent =
//        place.formatted_phone_number;
//  } else {
//    document.getElementById('iw-phone-row').style.display = 'none';
//  }

//  // Assign a five-star rating to the hotel, using a black star ('&#10029;')
//  // to indicate the rating the hotel has earned, and a white star ('&#10025;')
//  // for the rating points not achieved.
//  if (place.rating) {
//    var ratingHtml = '';
//    for (var i = 0; i < 5; i++) {
//      if (place.rating < (i + 0.5)) {
//        ratingHtml += '&#10025;';
//      } else {
//        ratingHtml += '&#10029;';
//      }
//    document.getElementById('iw-rating-row').style.display = '';
//    document.getElementById('iw-rating').innerHTML = ratingHtml;
//    }
//  } else {
//    document.getElementById('iw-rating-row').style.display = 'none';
//  }

//  // The regexp isolates the first part of the URL (domain plus subdomain)
//  // to give a short URL for displaying in the info window.
//  if (place.website) {
//    var fullUrl = place.website;
//    var website = hostnameRegexp.exec(place.website);
//    if (website == null) {
//      website = 'http://' + place.website + '/';
//      fullUrl = website;
//    }
//    document.getElementById('iw-website-row').style.display = '';
//    document.getElementById('iw-website').textContent = website;
//  } else {
//    document.getElementById('iw-website-row').style.display = 'none';
//  }


//  
//}

google.maps.event.addDomListener(window, 'load', initialize);

$(document).ready(function() {
    $(".web_search").on('click', getUserLocation);
    
$("#list").on('click','li',(function() {
	if ($(this).attr('class') == undefined){
		$(this).attr('class','active')
		var selected = $(this).attr('value');
        if (selected == "food") {
            selectedTypes = (food);
            search(place, selectedTypes, MARKER_food)
        }
        if (selected == "accommodation") {
            selectedTypes = (accommodation);
            search(place, selectedTypes, MARKER_accommodation)
        }
        if (selected == "entertainment") {
            selectedTypes = (entertainment);
            search(place, selectedTypes, MARKER_entertainment)
        }
        if (selected == "culture") {
            selectedTypes = (culture);
            search(place, selectedTypes, MARKER_culture)
        }
        if (selected == "nature") {
            selectedTypes = (nature);
            search(place, selectedTypes, MARKER_nature)
        }
        if (selected == "shopping") {
            selectedTypes = (shopping);
            search(place, selectedTypes, MARKER_shopping)
        }
        if (selected == "sports") {
            selectedTypes = (sports);
            search(place, selectedTypes, MARKER_sports)
        }
        if (selected == "transp") {
            selectedTypes = (transp);
            search(place, selectedTypes, MARKER_transp)
        }
        if (selected == "helpful") {
            selectedTypes = (helpful);
            search(place, selectedTypes, MARKER_helpful)
        }
		
		//alert(selectedTypes); 

        //search(place, selectedTypes)

	}else{
		$(this).removeAttr("class");
//        if (selected == "food") removeItem(selectedTypes, food);
//        if (selected == "accommodation") removeItem(selectedTypes, accommodation);
//        if (selected == "entertainment") removeItem(selectedTypes, entertainment);
//        if (selected == "culture") removeItem(selectedTypes, culture);
//        if (selected == "nature") removeItem(selectedTypes, nature);
//        if (selected == "shopping") removeItem(selectedTypes, shopping);
//        if (selected == "sports") removeItem(selectedTypes, sports);
//        if (selected == "transp") removeItem(selectedTypes, transp);
//        if (selected == "helpful") removeItem(selectedTypes, accommodation);
	}
}));
})

function removeItem(array, list){
    for(var i in array){
        for(var j in list){
            if(array[i]==item[j]){
                array.splice(i,1);
                break;
            }
        }
    }
}



function getUserLocation() {
    if (userLocation == undefined) {
        if (navigator.geolocation)
            navigator.geolocation.getCurrentPosition(handleGetCurrentPosition, onError);
    }

    function handleGetCurrentPosition(location) {
        userLocation = location;
        //map.setCenter(new GLatLng(location.coords.latitude, location.coords.longitude));
        alert(location.coords.latitude  +location.coords.longitude);
    }
    
    function onError() {
        alert("error");
    }
}

